package common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import base.pageModel.base.Json;
import common.enums.ResultCodeEnum;
import common.exception.ServiceException;

/**
 * Exception工具类
 * 
 * @author guixin
 * 
 */
public class ExceptionUtil {

	private static final Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);

	/**
	 * 返回错误信息字符串
	 * 
	 * @param ex
	 *            Exception
	 * @return 错误信息字符串
	 */
	public static void logExceptionMessage(Exception e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		String errorMessage = sw.toString();
		logger.error(errorMessage);
		pw.close();
		try {
			sw.close();
		} catch (IOException ex) {
			logger.error("ex",ex);
		}
	}

	/**
	 * 封装返回信息json
	 * 
	 * 此异常为可预见的(例如没有权限.名字重复的)
	 * @param e
	 * @param json
	 */
	public static void fillMsg(ServiceException s, Json json) {
		json.setResultCode(s.getErrorCode());
		json.setErrorMsg(s.getMessage());
		logger.error("错误码:{},错误信息:{}",s.getErrorCode(),s.getMessage());
	}

	/**
	 * 封装返回信息json
	 * 
	 * 此异常为不可预见的(如空指针异常等)
	 * @param e
	 * @param json
	 */
	public static void errorMsg(Exception e, Json json) {
		json.setResultCode(ResultCodeEnum.ERROR.getValue());
		json.setErrorMsg(ResultCodeEnum.ERROR.getLabel());
		logExceptionMessage(e);
	}

}
